package stc.skymobi.netty.handler.codec.esb;

import org.apache.commons.collections.Closure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import stc.skymobi.bean.esb.core.AbstractEsbM2ASignal;
import stc.skymobi.bean.esb.core.EsbAccess2ModuleSignal;
import stc.skymobi.netty.transport.Sender;
import stc.skymobi.netty.transport.TransportUtils;
import stc.skymobi.util.Identifyable;
import stc.skymobi.util.MutableIdentifyable;

public abstract class DefaultEsbBusyHandler implements Closure {

    private static Logger logger = LoggerFactory.getLogger(DefaultEsbBusyHandler.class);

    @Override
    public void execute(Object input) {
        AbstractEsbM2ASignal response = createResponse();
        if (input instanceof Identifyable && response instanceof MutableIdentifyable) {
            ((MutableIdentifyable) response).setIdentification(((Identifyable) input).getIdentification());
        }
        if (input instanceof EsbAccess2ModuleSignal) {
            response.setDstESBAddr(((EsbAccess2ModuleSignal) input).getSrcESBAddr());
            response.setSrcESBAddr(((EsbAccess2ModuleSignal) input).getDstESBAddr());
            response.setSeqNum(((EsbAccess2ModuleSignal) input).getSeqNum());

            response.setTerminalAccessInfo(((EsbAccess2ModuleSignal) input).getTerminalAccessInfo());
            try {
                response.setTerminalMessageHeader(((EsbAccess2ModuleSignal) input).getTerminalMessageHeader().clone().exchangeSrcDstModule());
                response.getTerminalMessageHeader().setFlags((short) 0x100);
                response.getTerminalMessageHeader().setSrcModule(((EsbAccess2ModuleSignal) input).getDstESBAddr());
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
            // send response
            Sender sender = TransportUtils.getSenderOf(input);
            if (logger.isDebugEnabled()) {
                logger.debug("SendClientRespState={}", response);
            }
            if (sender != null) {
                sender.send(response);
            } else {
                logger.error("getSender error!");
            }
        }
    }

    protected abstract AbstractEsbM2ASignal createResponse();
}
